package com.gugee.tiktok.common.model.dal.blogger;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gugee.tiktok.common.model.mysql.Aweme;
import com.gugee.tiktok.common.model.mysql.AwemeComment;

import com.xiguaji.boot.filecenter.FileTemplate;
import com.xiguaji.boot.toolkit.DateTimeUtils;
import lombok.SneakyThrows;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class AwemeCommentRepository {

    private  String KEY_PREFIX = "video_comment";

    @Value("${xiguaji.oss.bucket.tiktok.videoComment}")
    private String BUCKET_NAME = "xigua-tiktok-comment";

    @Autowired
    ObjectMapper objectMapper;

    @Autowired(required = false)
    FileTemplate fileTemplate;

    @Autowired
    AwemeRepository awemeRepository;

    @SneakyThrows
    public void save(long awemeId, List<AwemeComment> commentProperties) {
        byte[] bytes = objectMapper.writeValueAsBytes(commentProperties);
        if (fileTemplate == null) return;
        fileTemplate.putObject(BUCKET_NAME, KEY_PREFIX + awemeId, bytes);
    }

    /**
     * @param awemeId
     * @param millisecond
     * @param commentProperties
     */
    @SneakyThrows
    public void saveWithTime(long awemeId,long millisecond ,List<AwemeComment> commentProperties) {
        byte[] bytes = objectMapper.writeValueAsBytes(commentProperties);
        if (fileTemplate == null) return;
        //如果不存在就去查数据库
        if(millisecond <= 0){
           val aweme = awemeRepository.findByoAwemeId(awemeId);
           if(aweme.isPresent()){
               millisecond = aweme.get().getOCreateTime();
           }
        }
        String time = DateUtil.format(DateTimeUtils.localDateTimeBySecond(millisecond),"yyyyMMdd");
        String myKey = KEY_PREFIX +"_" + time +"/" + awemeId;
        fileTemplate.putObject(BUCKET_NAME, myKey, bytes);
    }

    /**
     * 获取对象
     * @param awemeId
     * @return
     */
    public String get(long awemeId,int time) {
        if (fileTemplate == null) {
            return null;
        }
        return fileTemplate.getAsString(BUCKET_NAME, KEY_PREFIX +"_" + time +"/" + awemeId);
    }
}
